package com.zige.zige.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.zige.zige.R;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.db.ProviceCityDao;
import com.zige.zige.dialog.CitySelectDialog;
import com.zige.zige.dialog.InterceptionImageDialog;
import com.zige.zige.pojo.Place;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.pojo.VideoTags;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.DateUtils;
import com.zige.zige.utils.DeleteRepeated;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.VolleyImageUtils;
import com.zige.zige.view.CircleImageView;
import com.zige.zige.view.MyGridView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Fei on 2015/11/5.
 */
public class PersonalInformationActivity extends BaseActivity implements View.OnClickListener, InterceptionImageDialog.HeadIconPathListener, CitySelectDialog.CitySelectDialogListener {

    private PersonalInformationActivity activity;

    private ImageView image_bg;
    private LinearLayout lay_back;
    private TextView tv_titlet;
    private CircleImageView imageView;
    private Button btn_ok;

    /**
     * 宝贝信息
     */
    private EditText ed_baby_nickname;
    private RadioGroup rg_baby_sex;
    private TextView tv_baby_birthday;
    private String babysex, babyBirthday;
    private RadioButton rg_sex_boy, rg_sex_girl;

    private MyGridView gridView;
    private ArrayList<VideoTags> mList = new ArrayList<>();
    Adapter adapter = new Adapter();
    private boolean press = true;

    private LinearLayout lay_address;
    private TextView tv_userAddress;

    /**
     * 父母信息
     */
    private EditText ed_parents_nickname;
    private RadioGroup rg_parents_identity;
    private String parents_identity;
    private Spinner sp_province, sp_city;
    private RadioButton rb_father, rg_mather;

    String province, city, myAddress;

    private String headImagePath, headImageName, headImageUrl;


    private UserInfo userInfo;
    private String tags;
    private Button btn_tomodfy;

    private ProviceCityDao dao;
    private final int QUREY_PROVINCE = 0;
    private final int QUREY_CITY = 1;

    private ArrayAdapter<String> provincesAdapter;
    private ArrayAdapter<String> citysAdapter;

    private List<Place> provinces;
    private List<String> provinceNames = new ArrayList<>();


    ;
    private List<Place> citys;
    private List<String> citynames = new ArrayList<>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case QUREY_PROVINCE:
                    provinceNames.clear();
                    for (Place place : provinces) {
                        provinceNames.add(place.name);
                    }
                    provincesAdapter = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_item, provinceNames);
                    provincesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    sp_province.setAdapter(provincesAdapter);
                    break;
                case QUREY_CITY:
                    citynames.clear();
                    for (Place place : citys) {
                        citynames.add(place.name);
                    }
                    if (citysAdapter == null) {
                        citysAdapter = new ArrayAdapter<String>(activity, android.R.layout.simple_spinner_item, citynames);
                        citysAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        sp_city.setAdapter(citysAdapter);
                    }
                    citysAdapter.notifyDataSetChanged();
                    break;

            }
        }
    };


    Calendar calendar = Calendar.getInstance();
    String imageCacheFile = Environment.getExternalStorageDirectory().toString()+"/LittleZebra/image";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.activity_personalinformation);
        dao = new ProviceCityDao(this);
        activity = this;
        userInfo = application.getUserInfo();
        headImageUrl = userInfo.headPortraitUrl;
        getVideoTags();
        setImageCacheFile();

        findView();
        initView();


    }

    private void  setImageCacheFile(){
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/Littlezebra");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }
    }
    private void initView() {
        textTags = DeleteRepeated.delet(application.getUserInfo().videoTags).replace(" ", "");

        tv_titlet = serchViewById(R.id.title_name);
        tv_titlet.setText("个人资料");
        btn_ok = serchViewById(R.id.btn_okey);
        btn_ok.setOnClickListener(this);
        image_bg = serchViewById(R.id.image_bg);
        image_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InterceptionImageDialog dialog = new InterceptionImageDialog();
                dialog.show(getFragmentManager(), "dialog");
            }
        });
        imageView = serchViewById(R.id.head_imged);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InterceptionImageDialog dialog = new InterceptionImageDialog();
                dialog.show(getFragmentManager(), "dialog");
            }
        });

        gridView = serchViewById(R.id.gridView);
        gridView.setAdapter(adapter);

        /**宝贝*/
        ed_baby_nickname = serchViewById(R.id.baby_nickname);
        if(userInfo.childName==null||!userInfo.childName.equals("null")){
            ed_baby_nickname.setText(userInfo.childName);
        }else {
            ed_baby_nickname.setHint("请给宝宝起个名字吧！");
        }

        rg_baby_sex = serchViewById(R.id.rg_sex);

        rg_baby_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int radioButtonId = group.getCheckedRadioButtonId();
                RadioButton radioButton = (RadioButton) PersonalInformationActivity.this.findViewById(radioButtonId);
                babysex = String.valueOf(radioButton.getText());
            }
        });

        rg_sex_boy = serchViewById(R.id.rg_sex_boy);
        rg_sex_girl = serchViewById(R.id.rg_sex_girl);
        if (userInfo.childSex.equals("男")) {
            rg_baby_sex.check(rg_sex_boy.getId());
        } else {
            rg_baby_sex.check(rg_sex_girl.getId());
        }
        tv_baby_birthday = serchViewById(R.id.tv_pbaby_birthday);
        if(userInfo.childBirthday!=null&&!userInfo.childBirthday.equals("null")){
            tv_baby_birthday.setText(DateUtils.timeStampToDated(userInfo.childBirthday));
        }else {
            tv_baby_birthday.setText("请选择宝宝生日");
        }
        babyBirthday = tv_baby_birthday.getText().toString();
        tv_baby_birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new DatePickerDialog(PersonalInformationActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        babyBirthday = String.valueOf(year) + "-" + String.valueOf(monthOfYear + 1) + "-" + String.valueOf(dayOfMonth);
                        tv_baby_birthday.setText(babyBirthday);

                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
        /**返回键*/
        lay_back = serchViewById(R.id.lay_back);
        lay_back.setOnClickListener(this);

        /**家长身份*/
        ed_parents_nickname = serchViewById(R.id.parents_nickname);
        if (userInfo.parentName.equals("null")) {
            ed_parents_nickname.setHint("您的昵称还未填写");
        } else {
            ed_parents_nickname.setText(userInfo.parentName);
        }
        rg_parents_identity = serchViewById(R.id.rg_parents_identity);
        rg_parents_identity.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int radioButtonId = group.getCheckedRadioButtonId();
                RadioButton radioButton = (RadioButton) activity.findViewById(radioButtonId);
                parents_identity = String.valueOf(radioButton.getText());
            }
        });
        rb_father = serchViewById(R.id.rb_father);
        rg_mather = serchViewById(R.id.rg_mather);
        if (userInfo.parentIdentity.equals("父亲")) {
            rg_parents_identity.check(rb_father.getId());
        } else {
            rg_parents_identity.check(rg_mather.getId());
        }
        lay_address = serchViewById(R.id.lay_adress);
        tv_userAddress = serchViewById(R.id.tv_useraddress);
        lay_address.setVisibility(View.GONE);
        if (application.getUserInfo().address.equals("null")) {
            tv_userAddress.setHint("请选择您所在的地址");
        } else {
            tv_userAddress.setText(application.getUserInfo().address);
        }
        myAddress = tv_userAddress.getText().toString();


        btn_tomodfy = serchViewById(R.id.btn_tomodfy);
        btn_tomodfy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CitySelectDialog dialog = new CitySelectDialog();
                dialog.show(getFragmentManager(), "dialog");
            }
        });
    }

    private ArrayList<VideoTags> getListItems() {
        return mList;
    }


    @Override
    public void OnCitySelectDialogListenerInputComplete(String address) {
        myAddress = address;
        tv_userAddress.setText(myAddress);
    }

    @Override
    public void OnHeadIconPath(String path) {
        headImagePath = path;
        headImageName = getFileName(headImagePath);
        headImageUrl = getQniuImageUrl(headImageName);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (headImagePath == null) {
            headImagePath = application.getUserInfo().headPortraitUrl;
            if(TextUtils.isEmpty(userInfo.headPortraitUrl)){
                image_bg.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
            }else {
                image_bg.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
                VolleyImageUtils.displayImage(headImagePath, imageView, activity);
            }
        } else {
            Bitmap bitmap = getLoacalBitmap(headImagePath);
            imageView.setImageBitmap(bitmap);
        }

    }

    private void findView() {
        sp_province = (Spinner) findViewById(R.id.sp_myprovince);
        sp_province.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
                if (citys != null)
                    citys.clear();
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        citys = dao.qureyAllCityByProvice(String.valueOf(position + 1));
                        handler.sendEmptyMessage(QUREY_CITY);
                    }
                }.start();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        sp_city = (Spinner) findViewById(R.id.sp_mycity);
        sp_city.setPrompt("市");
        setProvinceSpinner();
    }

    private void setProvinceSpinner() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                provinces = dao.qureyAllProvice();
                handler.sendEmptyMessage(QUREY_PROVINCE);
            }
        }.start();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_back:
                finish();
                break;
            case R.id.btn_okey:
                showLoadingDialog();
                if (!headImageUrl.equals(application.getUserInfo().headPortraitUrl) ) {
                    showLoadingDialog();
                    getQiNiuToken();
                } else {
                    showLoadingDialog();
                    setUserInfo(userInfo.headPortraitUrl);
                }
                break;

        }
    }

    private void savaData() {
        String babyName = (ed_baby_nickname.getText().toString()).replace(" ", "");
        String parmentName = (ed_parents_nickname.getText().toString()).replace(" ", "");
        if (!babyName.equals(application.getUserInfo().childName.replace(" ", ""))
                || !headImageUrl.equals(application.getUserInfo().headPortraitUrl)
                || !babysex.replace(" ", "").equals(userInfo.childSex.replace(" ", ""))
                || !DateUtils.getTime(babyBirthday.replace(" ", "")).equals(application.getUserInfo().childBirthday.replace(" ", ""))
                || !DeleteRepeated.delet(textTags).replace(" ", "").equals(DeleteRepeated.delet(application.getUserInfo().videoTags).replace(" ", ""))
                || !parmentName.equals(application.getUserInfo().parentName.replace(" ", ""))
                || !parents_identity.replace(" ", "").equals(application.getUserInfo().parentIdentity.replace(" ", ""))
                || !application.getUserInfo().locadHeadUrl.equals(application.getUserInfo().headPortraitUrl)
                || !tv_userAddress.getText().toString().equals(application.getUserInfo().address)) {

            showDialog();
        } else {
            finish();
            headImagePath = null;
        }

    }


    private void showDialog() {
        View view = View.inflate(activity, R.layout.dialog_user_save, null);
        final Dialog alertDialog = new Dialog(activity, R.style.theme_dialog);
        alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        alertDialog.setContentView(view);


        view.findViewById(R.id.btn_ok_cf).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                alertDialog.dismiss();
                if (!headImageUrl.equals(application.getUserInfo().headPortraitUrl) ) {
                    showLoadingDialog();
                    getQiNiuToken();
                } else {
                    showLoadingDialog();
                    setUserInfo(userInfo.headPortraitUrl);
                }
            }
        });
        view.findViewById(R.id.btn_canner_cf).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                finish();
            }
        });
        alertDialog.show();
    }


    private void getVideoTags() {
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(null, activity, UrlConsts.VIDEO_TAGS) {
            @Override
            protected void handleError() {
                super.handleError();
                closeLoadingDialog();
            }
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    closeLoadingDialog();
                    if (code == 0000) {
                        closeLoadingDialog();
                        JSONArray array = object.getJSONArray("tagList");
                        int size = array.length();
                        for (int i = 0; i < size; i++) {
                            JSONObject jsonObject = array.getJSONObject(i);
                            VideoTags videoTags = new VideoTags();
                            videoTags.parsefromJSON(jsonObject.toString());
                            getListItems().add(videoTags);
                        }
                    } else {
                        throw new Exception(msg);
                    }
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    showErrorDialog( e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                    closeLoadingDialog();
                }
            }
        });
    }


    /***
     * 修改之后的视频分类标签
     * tags
     */
    String textTags;

    private class Adapter extends BaseAdapter {
        final Map<Integer, String> map = new HashMap<Integer, String>();

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(activity, R.layout.gridview_videotype_item, null);
                viewHolder.tv_type = (Button) convertView.findViewById(R.id.tv_type);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            VideoTags videoTags = mList.get(position);
            viewHolder.tv_type.setText(videoTags.videoTags);

            if (userInfo.videoTags.contains(viewHolder.tv_type.getText())) {
                viewHolder.tv_type.setBackgroundResource(R.drawable.video_type_selector);
                map.put(position, viewHolder.tv_type.getText().toString());
                viewHolder.tv_type.setSelected(true);
                viewHolder.tv_type.isSelected();
                viewHolder.tv_type.setTextColor(getResources().getColor(R.color.white));
            } else {
                viewHolder.tv_type.setBackgroundResource(R.drawable.video_type_normal);
                viewHolder.tv_type.setSelected(false);
                viewHolder.tv_type.setTextColor(getResources().getColor(R.color.color_6A6A6A));
            }
            viewHolder.tv_type.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    textTags = null;
                    press = !viewHolder.tv_type.isSelected();
                    if (press) {
                        viewHolder.tv_type.setSelected(true);
                        viewHolder.tv_type.setBackgroundResource(R.drawable.video_type_selector);
                        viewHolder.tv_type.setTextColor(getResources().getColor(R.color.white));
                        String bu = viewHolder.tv_type.getText().toString();
                        map.put(position, bu);
                    } else {
                        viewHolder.tv_type.setBackgroundResource(R.drawable.video_type_normal);
                        viewHolder.tv_type.setSelected(false);
                        map.remove(position);
                        viewHolder.tv_type.setTextColor(getResources().getColor(R.color.color_6A6A6A));

                    }
                    textTags = (map.values().toString()).replace("[", "").replace("]", "");
                }
            });
            return convertView;
        }
    }


    class ViewHolder {
        Button tv_type;
    }


    /**
     * 获取七牛token
     */

    private void getQiNiuToken() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("fileKey", headImageName);
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params, activity, UrlConsts.GET_QINIU_TOKEN) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    if (code == 0000) {
                        String qiNiuToken = object.getString("qiniuToken");
                        UploadManager uploadManager = new UploadManager();
                        uploadManager.put(headImagePath, headImageName, qiNiuToken, new UpCompletionHandler() {
                            @Override
                            public void complete(String s, ResponseInfo responseInfo, JSONObject jsonObject) {
                                setUserInfo(headImageUrl);
                                if (200 == responseInfo.statusCode) {
                                    setUserInfo(headImageUrl);
                                } else {
                                    closeLoadingDialog();
                                    showErrorDialog( "修改图像失败，请重新提交");
                                }
                            }
                        }, null);

                    } else {
                        closeLoadingDialog();
                        showErrorDialog("网络异常，上传失败");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    String childSex;
    private void setUserInfo(String headIconUrl) {

        String deviceId = SystemUtils.getDeviceKey(activity);
        String uid = userInfo.userID;
        String childName = ed_baby_nickname.getText().toString();
        if(babysex.equals("男")){
            childSex= "M";
        }else if(babysex.equals("女")){
            childSex= "F";
        }
        String childBirthday = tv_baby_birthday.getText().toString();
        String parentName = ed_parents_nickname.getText().toString();
        String parentIdentity = parents_identity;

        HashMap<String, String> parmas = new HashMap<>();
        parmas.put("deviceId", deviceId);
        parmas.put("uid", uid);
        parmas.put("childName", childName);
        parmas.put("childSex", childSex);
        parmas.put("childBirthday", childBirthday);
        parmas.put("tags", textTags);
        parmas.put("parentName", parentName);
        parmas.put("parentIdentity", parentIdentity);
        parmas.put("address", myAddress);
        parmas.put("iconUrl", headIconUrl);
        Log.e("wu",childSex);


        TaskExecutor.getInstance().execute(new PostRequestTask(parmas, activity, UrlConsts.MODIFY_USERINFO) {
            @Override
            protected void handleError() {
                super.handleError();
                closeLoadingDialog();
            }
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    if (code == 0000) {
                        closeLoadingDialog();
                        showErrorDialog("修改资料成功");
                        UserInfo userInfo = new UserInfo();
                        userInfo.parsefromJSON(object.getString("userInfo"));
                        application.setUserInfo(userInfo);
                        startActivity(new Intent(activity, HomedActivity.class));
                        finish();
                        headImagePath = null;

                    } else if (code == 7777) {
                        showErrorDialog( "您有资料未填写");
                    }
                } catch (Exception e) {
                    showErrorDialog(e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                    closeLoadingDialog();
                }
            }
        });

    }



    /**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据路径得到文件得到文件名
     *
     * @param pathandname
     * @return
     */
    public String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }
    }

    /**
     * 拼接七牛图片地址
     *
     * @param name
     * @return
     */
    private String getQniuImageUrl(String name) {
        return "http://" + "7xkpsq.com2.z0.glb.qiniucdn.com" + "/" + name;
    }
}
